package br.com.srv.config;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.StringRefAddr;

import org.apache.commons.dbcp.BasicDataSource;

import br.com.srv.exception.FFServiceException;

public class ConfiguracaoJDBCDataSource {
	
	public final static String IP_ADDRESS = "localhost";
	public final static String PORTA = "9000";
	public final static String URL_JDBC = "jdbc:mysql://localhost/ffService";
	public final static String USER_JDBC = "root";
	public final static String PWD_JDBC = "root";
	public final static String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
	
	private final static String NAME_JDBC = "jdbc/ffService";

	public ConfiguracaoJDBCDataSource() throws FFServiceException {

		try {
			System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
					"com.sun.jndi.fscontext.RefFSContextFactory");
			System.setProperty(Context.PROVIDER_URL, "file:///jndi");
			InitialContext ic = new InitialContext();

			// Construct BasicDataSource reference
			Reference ref = new Reference(
					"javax.sql.DataSource", "org.apache.commons.dbcp.BasicDataSourceFactory", null);

			ref.add(new StringRefAddr("driverClassName", "com.mysql.jdbc.Driver"));
			ref.add(new StringRefAddr("url", "jdbc:mysql://localhost/ffService"));
			ref.add(new StringRefAddr("username", "root"));
			ref.add(new StringRefAddr("password", "root"));
			ref.add(new StringRefAddr("maxActive", "15"));
			
			ic.rebind(NAME_JDBC, ref);
			
		} catch (NamingException e) {
			throw new FFServiceException(e, "Erro JNDI");
		}

	}

	public static Connection pegarConexao() throws FFServiceException {
		
		Connection conn = null;
		
		try {
			InitialContext ic2 = new InitialContext();
			BasicDataSource dataSource = (BasicDataSource) ic2
					.lookup(NAME_JDBC);
			conn = dataSource.getConnection();
		} catch (NamingException e) {
			throw new FFServiceException(e, "Erro ao tentar localizar jdbc/basic JNDI");
		} catch (SQLException e) {
			throw new FFServiceException(e, "Erro de SQL");
		} finally {
			return conn;
		}
	}

}
